<template>
  <div id="login-container">
    <div id=login>
      <h1>{{ sysInfo.name }}

      </h1>
      <h4>{{ sysInfo.desc }}<br>
        <el-tag size="mini" type="success">
          {{ sysInfo.version }}
        </el-tag>
      </h4>
      <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="rules"
          class="loginForm"
          status-icon
      >
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" autocomplete="off" placeholder="用户名"/>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="loginForm.password" autocomplete="off" placeholder="密码" show-password type="password"
                    @keyup.enter.native="login"/>
        </el-form-item>

        <el-form-item>
          <el-button v-if="!needCheck" style="width: 100%" type="primary" @click="login">登录</el-button>
          <Verify v-if="needCheck"
                  ref="verify"
                  :captchaType="'blockPuzzle'"
                  :imgSize="{ width: '400px', height: '200px' }"
                  :mode="'fixed'"
                  @success="success"
          ></Verify>
        </el-form-item>
      </el-form>

    </div>
  </div>
</template>

<script>
import Verify from "../../components/verifition/Verify";
import {loginApi, needCheckAPI} from "../../api/login";
import {sysInfoApi} from "@/api/common";

export default {
  data() {
    return {
      needCheck: false,
      sysInfo: {},
      loginForm: {},
      rules: {
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
        ],
        password: [{required: true, message: "请输入密码", trigger: "blur"}],
      },
    };
  },
  components: {
    Verify,
  },
  methods: {
    success(params) {
      this.loginForm.captcha = params;
      this.login();
    },
    async loadNeedCheck() {
      this.needCheck = await needCheckAPI();
    },
    login() {
      loginApi(this.loginForm).then((loginInfo) => {
        this.$message({
          message: `登录成功`,
          type: "success",
        });
        localStorage.setItem("login_token", loginInfo.token);
        this.$router.push("/");
      }).catch(() => {
        this.loginForm.password = null;
        this.loadNeedCheck();
      });
    },
  },
  created() {
    sysInfoApi().then(info => this.sysInfo = info);
    this.loadNeedCheck();
  }
};
</script>
<style scoped>
#login-container {
  width: 100%;
  height: 100%;
  background: #f2f6fc;
  color: #409eff;
}

#login {
  margin: 0 auto;
  padding-top: 50px;
  width: 400px;
  text-align: center;
}

#login h1 {
  font-size: 50px;
  margin-top: 30px;
}

#login h4 {
  margin-top: 10px;
  margin-bottom: 20px;
}
</style>
